package sk.stuba.fiit.repka.dp.db;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.hsqldb.server.Server;

public final class DatabaseController {
	private static Logger logger = Logger.getLogger(DatabaseController.class);
	
	private static final String URL = "jdbc:hsqldb:hsql://localhost/wsrequirementsdb";
	private static final String USER = "SA";
	private static final String PASSWORD = "";
	
	private Server server;
	private Connection con;
	
	public Connection getCon() {
		return this.con;
	}
	
	public void createConnection() throws SQLException {
		//start server
		this.server = new Server();
		server.setAddress("localhost");
		server.setDatabaseName(0, "wsrequirementsdb");
		server.setDatabasePath(0, "file:hsqldb" + File.separator + "hsqldb" + File.separator + "repkadb");
		server.setTrace(true);
		server.start();
		
		//create connection
		this.con = DriverManager.getConnection(URL, USER, PASSWORD);
		logger.info("Connection to database created successfully.");
	}
	
	public void closeConnection(Connection c) throws SQLException {
		c.close(); //close connection
		this.server.stop(); //stop server
		logger.info("Connection to database closed successfully");
	}
}
